<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use think\facade\Db;
use think\facade\Cache;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;

use app\common\library\Excel;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;

class OrderCheckDisputeLogic
{
    protected $model = null;
    public function __construct()
    {
        $this->model = new \app\order\model\OrderCheck();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $date = $params['date'] ?? [];
        $ordercheck_id = $params['ordercheck_id'] ?? [];
        $limit = $params['limit'] ?? 10;
        $type   = $params['type'] ?? '';
        $status = $params['status'] ?? '0';
        $where = [];
        
        if(!empty($ordercheck_id)){
            $where['ordercheck_id'] = $ordercheck_id;
        }
        if(!empty($date)){
            $where['timedate'] = $date;
        }

        if(!empty($type)){
            $where[] = array('type', 'LIKE', '%' . trim($type) . '%');
        }

        if(!empty($status)){
            $where['status'] = $status;
        }

        $list = Db::name('ordercheck_dispute')
            ->where($where)
            ->order("id asc")
            ->paginate($limit);

        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            $lists[$k]['date'] = date('Y-m', $v['timedate']);
            switch ($v['status']) {
                case '0':
                    $lists[$k]['status'] = '匹配中';
                    break;
                case '1':
                    $lists[$k]['status'] = '已完成';
                    break;
                default:
                    $lists[$k]['status'] = '匹配中';
            }
        }
                
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $lists = [];
        $header = [];
        $header[] = ['月份', 'date'];
        $header[] = ['支付类型', 'type'];
        $header[] = ['转单号码', 'transfer_number'];
        $header[] = ['金额', 'cost'];
        $fileName = "export_Advaccount" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        if (!$data['date']) {
            return json(DefaultResponse(201, false, '请填写月份!', null));
        }
        if (!$data['type']) {
            return json(DefaultResponse(201, false, '请填写类型!', null));
        }
        $row = Db::name('ordercheck')
            ->where('date',$data['date'])
            ->where('type',$data['type'])
            ->find();
        if ($row) {
            return json(DefaultResponse(201, false, '已存在任务!', null));
        }

        $result = false;

        try {
            //广告账户
            $ordercheck['date'] = $data['date'];
            $ordercheck['time'] = strtotime($data['date']);
            $ordercheck['type'] = $data['type'];
            $ordercheck['status'] = $data['status'] ?? 0;

            $result = Db::name('ordercheck')->insert($ordercheck);
            if ($result !== false) {
                return json(DefaultResponse(200, true, '添加成功!', null));
            } else {
                return json(DefaultResponse(201, false, '添加失败!', null));
            }
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '广告账户已存在!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));

    }

    public function find($id)
    {
        if (!$id) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $row = $this->model->find($id);
        
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }

        switch ($row['type']) {
            case '1':
                $row['type'] = '争议成本';
                break;
            case '2':
                $row['type'] = '物流成本';
                break;
            case '3':
                $row['type'] = '采购成本';
                break;
            default:
                $row['type'] = '未知';
        }

        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        $row = $this->model->find($id);
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {
            
            //广告账户
            $ordercheck['status'] = $data['status'] ?? 0;
            $result = $row->save($ordercheck);

            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }
    
    /**
     * @desc   import
     * @author zhagnheng
     * @date   2024-07-27
     */
    public function import($url){
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelData        = isset($data[0]) ? $data[0] : $data;
        $excelData        = array_values($excelData);
        if(!$excelData)    return json(DefaultResponse(201, false, '暂无数据!', null));
        foreach($excelData as $v){
            MqTaskPushLogic::mq_task_push(
                '',
                // TODO异步导入
                // MqQueueName::QUEUE_ORDER_NEW_PRODUCT_UPLOAD_QUEUE,
                $v,
                false
            );
        }
        return json(DefaultResponse(200, false, '导入成功!', null));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function CheckDispute($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $tabstatus   = $params['tabstatus'] ?? 'All';
        $type   = $params['type'] ?? '';
        $date   = $params['date'] ?? [];
        $create_time   = $params['create_time'] ?? [];
        $createtime   = $params['createtime'] ?? [];
        $shop_id   = $params['shop_id'] ?? 0;
        $status   = $params['status'] ?? 0;
        $order_name   = $params['order_name'] ?? 0;
        $tracking_number   = $params['tracking_number'] ?? 0;
        $customDate = $params['customDate'] ?? 0;
        $where = [];
        if(!empty($createtime)){
            $where[]  = ['createtime', '>=', strtotime($createtime[0])];
            $where[]  = ['createtime', '<=', strtotime($createtime[1]) + 3600*24-1];
        }
        if(!empty($shop_id)){
            $where[] = ['shop_id','=',$shop_id];
        }
        if(!empty($order_name)){
            $where[] = array('order_name', 'LIKE', '%' . trim($order_name) . '%');
        }
        if(!empty($tracking_number)){
            $where[] = array('tracking_number', 'LIKE', '%' . trim($tracking_number) . '%');
        }
        if(!empty($type)){
            if($type == 'MatchSuccessful'){
                $where[] = ['order_id','>',0];
            }
            if($type == 'WaitingForAMatch'){
                $where[] = ['order_id','<=',0];
            }
        }
        //日期
        $where = $this->ProcessingDate($date,$where,$customDate,$create_time);
        
        //统计
        $Statistics = $this->Statistics($where);
        
        
        
        $shops = Db::name('shops')->field('id,name')->select()->toarray();
        $shop_map = array_column($shops,'name','id');
        switch ($tabstatus) {
            case 'afterpay':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_afterpay')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                
                $totals = $list->total();
                break;
            case 'airwallex':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_airwallex')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'paypal':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_paypal')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'stripe':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_stripe')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'shopify':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_api')
                    ->where($where)
                    ->group('dispute_id')
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'All':
                $tables = [
                    'order_dispute_afterpay',
                    'order_dispute_airwallex',
                    'order_dispute_paypal',
                    'order_dispute_stripe',
                    'order_dispute_api'
                ];
                
                $lists = [];
                $totals = 0;
                foreach ($tables as $table) {
                    // if(!empty($status)){
                    //     $status = $this->ChangeStatewhere($status,$tabstatus);
                    //     $where[] = ['status','=',$status];
                    // }
                    $list = Db::name($table)
                        ->where($where)
                        ->order("disputetime desc")
                        ->paginate($limit);
                    $total = $list->total();
                    $list = $list->items();
                    foreach ($list as &$v) {
                        switch ($table) {
                            case 'order_dispute_afterpay':
                                $v['tabstatus'] = 'afterpay';
                                break;
                            case 'order_dispute_airwallex':
                                $v['tabstatus'] = 'airwallex';
                                break;
                            case 'order_dispute_paypal':
                                $v['tabstatus'] = 'paypal';
                                break;
                            case 'order_dispute_stripe':
                                $v['tabstatus'] = 'stripe';
                                break;
                            case 'order_dispute_api':
                                $v['tabstatus'] = 'shopify';
                                break;
                            default:
                        }
                        
                    }
                    $totals += $total;
                    $lists = array_merge($lists, $list);
                }
                break;
            default:
        }
        foreach ($lists as &$v) {
            if($v['OrderDeliveryTime'] > 0){
                $v['OrderDeliveryTime'] = date('Y-m-d',strtotime($v['OrderDeliveryTime']));
            }else{
                $v['OrderDeliveryTime'] = "暂无";
            }
            if($v['createtime'] > 0){
                $v['createtime'] = date('Y-m-d',$v['createtime']);
            }else{
                $v['createtime'] = "暂无";
            }
            if($v['disputetime'] > 0){
                $v['time'] = date('Y-m-d',$v['disputetime']);
            }else{
                $v['time'] = "";
            }
            if($tabstatus !== "All"){
                $v['tabstatus'] = $tabstatus;
            }
            if($v['fulfillment_status'] == 'fulfilled'){
                $v['fulfillment_status'] = '已发货';
            }elseif($v['fulfillment_status'] == 'partial'){
                $v['fulfillment_status'] = '部分发货';
            }else{
                $v['fulfillment_status'] = '未发货';
            }
            $v['shop_id'] = $v['shop_id'] ?? 0;
            $v['shop_name'] = $shop_map[$v['shop_id']] ?? "";
            $v['status'] = $this->ChangeState($v['status'],$tabstatus);
        }
        $data = [
            'list' => $lists,
            'total' => $totals,
            'spends' => $Statistics['spends'],
            'spends_Total' => $Statistics['spends_Total'],
        ];

        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
    * @desc    统计
    * @author  zhangheng
    */
    public function Statistics($where)
    {
        $spends = [];
        $spends_Total = 0;
        //afterpay1
        $count = Db::name('order_dispute_afterpay')
            ->where($where)
            ->where('api_type','afterpay_shecurve')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'afterpay(shecurve)',
            'count' => $count ?? 0,
        ];
        //afterpay2
        $count = Db::name('order_dispute_afterpay')
            ->where($where)
            ->where('api_type','afterpay_woobilly')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'afterpay(woobilly)',
            'count' => $count ?? 0,
        ];
        
        //airwallex
        $count = Db::name('order_dispute_airwallex')
            ->where($where)
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'airwallex',
            'count' => $count ?? 0,
        ];
        //paypal
        $count = Db::name('order_dispute_paypal')
            ->where($where)
            ->where('api_type','01xinfei')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'paypal(欣妃)',
            'count' => $count ?? 0,
        ];
        //paypal2
        $count = Db::name('order_dispute_paypal')
            ->where($where)
            ->where('api_type','02zeshengkang')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'paypal(泽生康)',
            'count' => $count ?? 0,
        ];
        //paypal3
        $count = Db::name('order_dispute_paypal')
            ->where($where)
            ->where('api_type','03shecurve')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'paypal(银川shecurve)',
            'count' => $count ?? 0,
        ];
        //stripe
        $count = Db::name('order_dispute_stripe')
            ->where($where)
            ->where('api_type','stripe01')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'stripe账号01',
            'count' => $count ?? 0,
        ];
         //stripe2
        $count = Db::name('order_dispute_stripe')
            ->where($where)
            ->where('api_type','stripe02')
            ->group('id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'stripe账号02',
            'count' => $count ?? 0,
        ];
        //shopifyPayment
        $count = Db::name('order_dispute_api')
            ->where($where)
            ->group('dispute_id')
            ->count();
        $spends_Total += (int)$count;
        $spends[] = [
            'platform' => 'shopifyPayment',
            'count' => $count ?? 0,
        ];
        $data['spends'] = $spends;
        $data['spends_Total'] = $spends_Total;
        return $data;
    }
    
    
    /**
    * @desc    整合日期
    * @author  zhangheng
    */
    public function ProcessingDate($date,$where,$customDate,$create_time)
    {
        if($date){
            $date[1] = date('Y-m-d', strtotime("+1 month", strtotime($date[1])));
        }
        if(!empty($customDate)){
            switch ($customDate) {
                case '1':
                    //实时
                    $yesterday = date('Y-m-d', time() - timezone());  
                    $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                    $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                    $where[]  = ['disputetime', '>=', $midnightYesterday];
                    $where[]  = ['disputetime', '<', $endOfYesterday]; 

                    break;
                case '2':
                    $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());
                    $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                    $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                    $where[]  = ['disputetime', '>=', $midnightYesterday];
                    $where[]  = ['disputetime', '<', $endOfYesterday]; 
                    break;
                case '3':
                    $yesterday = date('Y-m-d', time() - timezone());  
                    $yesterday  = strtotime($yesterday . ' 23:59:59');
                    
                    $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-2 day') - timezone()));  
                    $where[] = ['disputetime', '<', $yesterday];
                    $where[] = ['disputetime', '>=', $yesterdayEnd];

                    break;
                case '4':
                    $yesterday = date('Y-m-d', time() - timezone());  
                    $yesterday  = strtotime($yesterday . ' 23:59:59');

                    $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-6 day') - timezone()));  
                    $where[] = ['disputetime', '<', $yesterday];
                    $where[] = ['disputetime', '>=', $yesterdayEnd];

                    break;
                case '5':
                    $yesterday = date('Y-m-d', time() - timezone());  
                    $yesterday  = strtotime($yesterday . ' 23:59:59');

                    $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-29 day') - timezone()));  
                    $where[] = ['disputetime', '<', $yesterday];
                    $where[] = ['disputetime', '>=', $yesterdayEnd];

                    break;
                default:
            }
        }else{
            if($date){
                $where[] = ['disputetime', '<', strtotime($date[1])];
                $where[] = ['disputetime', '>=', strtotime($date[0])];
            }else if($create_time){
                $where[]  = ['disputetime', '>=', strtotime($create_time[0])];
                $where[]  = ['disputetime', '<=', strtotime($create_time[1]) + 3600*24-1];
            }
        }
        return $where;
    }
    
    /**
    * @desc    通道状态
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeState($status,$type)
    {
        if($type == 'stripe'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'paypal'){
            switch ($status) {
                case 'WAITING_FOR_SELLER_RESPONSE':
                    $status = '待处理';
                    break;
                case 'UNDER_REVIEW':
                    $status = '审核中';
                    break;
                case 'RESOLVED':
                    $status = '争议赢';
                    break;
                case 'LOST':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'afterpay'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'shopify'){
            switch ($status) {
                case 'needs_response':
                    $status = '待处理';
                    break;
                case 'under_review':
                    $status = '审核中';
                    break;
                case 'won':
                    $status = '争议赢';
                    break;
                case 'lost':
                    $status = '争议输';
                    break;
                default:
                    $status = '其他';
            }
        }
        if($type == 'airwallex'){
            switch ($status) {
                case 'LOST':
                    $status = '争议输';
                    break;
                case 'ACCEPTED':
                    $status = '争议输';
                    break;
                case 'WON':
                    $status = '争议赢';
                    break;
                case 'CHALLENGED':
                    $status = '审核中';
                    break;
                default:
                    $status = '其他';
            }
        }
        return $status;
    }
    /**
    * @desc    通道状态
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function ChangeStatewhere($status,$type)
    {
        if($type == 'stripe'){
            switch ($status) {
                case '待处理':
                    $status = 'needs_response';
                    break;
                case '审核中':
                    $status = 'under_review';
                    break;
                case '争议赢':
                    $status = 'won';
                    break;
                case '争议输':
                    $status = 'lost';
                    break;
                default:
                    $status = '';
            }
        }
        if($type == 'paypal'){
            switch ($status) {
                case '待处理':
                    $status = 'WAITING_FOR_SELLER_RESPONSE';
                    break;
                case '审核中UNDER_REVIEW':
                    $status = 'UNDER_REVIEW';
                    break;
                case '争议赢':
                    $status = 'RESOLVED';
                    break;
                case '争议输':
                    $status = 'LOST';
                    break;
                default:
                    $status = '';
            }
        }
        if($type == 'afterpay'){
            switch ($status) {
                case '待处理':
                    $status = 'needs_response';
                    break;
                case '审核中':
                    $status = 'under_review';
                    break;
                case '争议赢':
                    $status = 'won';
                    break;
                case '争议输':
                    $status = 'lost';
                    break;
                default:
                    $status = '';
            }
        }
        if($type == 'shopify'){
            switch ($status) {
                case '待处理':
                    $status = 'needs_response';
                    break;
                case '审核中':
                    $status = 'under_review';
                    break;
                case '争议赢':
                    $status = 'won';
                    break;
                case '争议输':
                    $status = 'lost';
                    break;
                default:
                    $status = '';
            }
        }
        if($type == 'airwallex'){
            switch ($status) {
                case '争议输':
                    $status = 'LOST';
                    break;
                case '争议输':
                    $status = 'ACCEPTED';
                    break;
                case '争议赢':
                    $status = 'WON';
                    break;
                case '审核中':
                    $status = 'CHALLENGED';
                    break;
                default:
                    $status = '其他';
            }
        }
        return $status;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function exportCheckDispute($params = [])
    {  
        $tabstatus   = $params['tabstatus'] ?? 'All';
        $type   = $params['type'] ?? '';
        $date   = $params['date'] ?? [];
        $create_time   = $params['create_time'] ?? [];
        $createtime   = $params['createtime'] ?? [];
        $shop_id   = $params['shop_id'] ?? 0;
        $status   = $params['status'] ?? 0;
        $order_name   = $params['order_name'] ?? 0;
        $tracking_number   = $params['tracking_number'] ?? 0;
        $customDate = $params['customDate'] ?? 0;
        $where = [];
        if(!empty($createtime)){
            $where[]  = ['createtime', '>=', strtotime($createtime[0])];
            $where[]  = ['createtime', '<=', strtotime($createtime[1]) + 3600*24-1];
        }
        if(!empty($shop_id)){
            $where[] = ['shop_id','=',$shop_id];
        }
        if(!empty($order_name)){
            $where[] = array('order_name', 'LIKE', '%' . trim($order_name) . '%');
        }
        if(!empty($tracking_number)){
            $where[] = array('tracking_number', 'LIKE', '%' . trim($tracking_number) . '%');
        }
        if(!empty($type)){
            if($type == 'MatchSuccessful'){
                $where[] = ['order_id','>',0];
            }
            if($type == 'WaitingForAMatch'){
                $where[] = ['order_id','<=',0];
            }
        }
        //日期
        $where = $this->ProcessingDate($date,$where,$customDate,$create_time);
        
        $shops = Db::name('shops')->field('id,name')->select()->toarray();
        $shop_map = array_column($shops,'name','id');
        $lists = [];
        switch ($tabstatus) {
            case 'afterpay':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $lists = Db::name('order_dispute_afterpay')
                    ->where($where)
                    ->order("disputetime desc")
                    ->select()->toarray();
                
                break;
            case 'airwallex':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $lists = Db::name('order_dispute_airwallex')
                    ->where($where)
                    ->order("disputetime desc")
                    ->select()->toarray();
                break;
            case 'paypal':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $lists = Db::name('order_dispute_paypal')
                    ->where($where)
                    ->order("disputetime desc")
                    ->select()->toarray();
                break;
            case 'stripe':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $lists = Db::name('order_dispute_stripe')
                    ->where($where)
                    ->order("disputetime desc")
                    ->select()->toarray();
                break;
            case 'shopify':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $lists = Db::name('order_dispute_api')
                    ->where($where)
                    ->group('dispute_id')
                    ->order("disputetime desc")
                    ->select()->toarray();
                break;
            case 'All':
                $tables = [
                    'order_dispute_afterpay',
                    'order_dispute_airwallex',
                    'order_dispute_paypal',
                    'order_dispute_stripe',
                    'order_dispute_api'
                ];
                foreach ($tables as $table) {
                    $list = Db::name($table)
                        ->where($where)
                        ->order("disputetime desc")
                        ->select()->toarray();
                    foreach ($list as &$v) {
                        switch ($table) {
                            case 'order_dispute_afterpay':
                                $v['tabstatus'] = 'afterpay';
                                break;
                            case 'order_dispute_airwallex':
                                $v['tabstatus'] = 'airwallex';
                                break;
                            case 'order_dispute_paypal':
                                $v['tabstatus'] = 'paypal';
                                break;
                            case 'order_dispute_stripe':
                                $v['tabstatus'] = 'stripe';
                                break;
                            case 'order_dispute_api':
                                $v['tabstatus'] = 'shopify';
                                break;
                            default:
                        }
                    }
                    $lists = array_merge($lists, $list);
                }
                break;
            default:
        }
        foreach ($lists as &$v) {
            if($v['OrderDeliveryTime'] > 0){
                $v['OrderDeliveryTime'] = date('Y-m-d',strtotime($v['OrderDeliveryTime']));
            }else{
                $v['OrderDeliveryTime'] = "暂无";
            }
            if($v['createtime'] > 0){
                $v['createtime'] = date('Y-m-d',$v['createtime']);
            }else{
                $v['createtime'] = "暂无";
            }
            if($v['disputetime'] > 0){
                $v['time'] = date('Y-m-d',$v['disputetime']);
            }else{
                $v['time'] = "";
            }
            if($tabstatus !== "All"){
                $v['tabstatus'] = $tabstatus;
            }
            if($v['fulfillment_status'] == 'fulfilled'){
                $v['fulfillment_status'] = '已发货';
            }elseif($v['fulfillment_status'] == 'partial'){
                $v['fulfillment_status'] = '部分发货';
            }else{
                $v['fulfillment_status'] = '未发货';
            }
            $v['shop_id'] = $v['shop_id'] ?? 0;
            $v['shop_name'] = $shop_map[$v['shop_id']] ?? "";
            $v['status'] = $this->ChangeState($v['status'],$tabstatus);
        }

        $header = [];
        $header[] = ['订单ID', 'order_id'];
        $header[] = ['渠道', 'tabstatus'];
        $header[] = ['争议时间', 'time'];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['争议状态', 'status'];
        $header[] = ['订单号', 'order_name'];
        $header[] = ['付款时间', 'createtime'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['发货时间', 'OrderDeliveryTime'];
        $header[] = ['物流单号', 'tracking_number'];
        $header[] = ['会话', 'conversations'];
        $header[] = ['邮箱', 'email'];
        $fileName = "exportCheckDispute" . time();

        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function ConversaList($params = [])
    {
        $email = $params['email'] ?? "";
        $limit = $params['limit'] ?? 10;
        if (empty($email)) {
            return json(DefaultResponse(201, false, '获取失败'));
        }
        $list = Db::name('conversations')
            ->field('slug,author,created_at,status,json')
            ->where('email',$email)
            ->order('created_at desc')
            ->paginate($limit);
        $lists = $list->items();

        foreach ($lists as &$v) {
            // $messages = [];
            $json = json_decode($v['json'],true);
            $v['last_customer_message'] = $json['last_customer_message']['body'] ?? "";
            $v['last_staff_message'] = $json['last_staff_message']['body'] ?? "";
            // if(!empty($json['last_customer_message'])){
            //     $message = [
            //         'body' => $json['last_customer_message']['body'],
            //         'created_at' => $json['last_customer_message']['created_at'],
            //         'role' => "customer",
            //     ];
            //     $messages[] = $message;
            // }
            // if(!empty($json['last_staff_message'])){
            //     $message = [
            //         'body' => $json['last_staff_message']['body'],
            //         'created_at' => $json['last_staff_message']['created_at'],
            //         'role' => "staff",
            //     ];
            //     $messages[] = $message;
            // }
            // $v['message'] = $messages;

            switch ($v['status']) {
                case '0':
                    $v['status'] = '未解决';
                    break;
                case '1':
                    $v['status'] = '挂起';
                    break;
                case '2':
                    $v['status'] = '已解决';
                    break;
                case '3':
                    $v['status'] = '垃圾邮件';
                    break;
                case '4':
                    $v['status'] = '存档';
                    break;
                case '5':
                    $v['status'] = '暂停';
                    break;
                case '6':
                    $v['status'] = '自动解决';
                    break;
                case '7':
                    $v['status'] = '聊天机器人删除';
                    break;
                case '8':
                    $v['status'] = '聊天机器人解决';
                    break;
                case '9':
                    $v['status'] = '垃圾邮件-由AI识别';
                    break;
                default:
                    $v['status'] = '未知';
                    break;
            }
        }
                
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    

    /**
    * @desc    StoreDisputeRate店铺争议率
    * @date    2025/7/16
    * @author  zhangheng
    */
    public function StoreDisputeRate($params = [])
    {
        $shops = Db::name('shops')
            ->field('id as shop_id,name as shop_name')
            ->where('status',1)
            ->select()
            ->toarray();
        $shop_map = array_column($shops,'shop_name','shop_id');

        $shop_id       = $params['shop_id'] ?? [];
        $createtime    = $params['createtime'] ?? [];
        // $createtime    = $params['createtime'] ?? ["2025-05-01","2025-05-31"];
        if (empty($shop_id)) {
            // return json(DefaultResponse(200, true, '获取成功', []));
            return json(DefaultResponse(201, false, '请选择店铺'));
        }
        if (empty($createtime)) {
            return json(DefaultResponse(201, false, '请选择订单付款时间'));
        }

        $where = [];
        $where[]  = ['shop_id', 'in', $shop_id]; 
        $where[] = ['createtime', '>=', strtotime($createtime['0'])];
        $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        $where2 = [];
        $where2[]  = ['disputeapi_status',"<>",'暂无争议'];

        $Dimension       = $params['Dimension'] ?? 1;
        if($Dimension == 1){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id') 
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')   
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        if($Dimension == 2){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%u") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()  
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%u") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        if($Dimension == 3){
            $list = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m") as date,
                COUNT(id) as quantity,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->order(['date' => 'asc','quantity' => 'desc'])
                ->select()  
                ->toArray();
            $list2 = Db::name('order_achievement')
                ->field('
                DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m") as date,
                COUNT(id) as dispute,shop_id')
                ->group('date,shop_id')  
                ->where($where)
                ->where($where2)
                ->order(['date' => 'asc','dispute' => 'desc'])
                ->select()  
                ->toArray();
        }
        // halt($list);
        $list_new = [];
        try { 
            $list_new = array_map(function($item) use ($list2,$shop_map,$Dimension) {
                $item['dispute'] = 0;
                foreach ($list2 as $item2) {
                    $item['DisputeRate'] = 0;
                    if ($item['date'] == $item2['date']) {
                        $item['dispute'] = $item2['dispute'];
                        if($item['dispute'] > 0){
                            $item['DisputeRate'] = number_format($item['dispute']/$item['quantity']*10000,0);
                            break;
                        }
                    }
                }
                
                if($Dimension == 2){
                    $item['date'] = str_replace('-','年',$item['date']);
                    $item['date'] = $item['date'].'周';
                }
                $item_new = [
                    'info' => "额外信息1额外信息1额外信息1额外信息1额外信息1额外信息1",
                    'shop' => "店铺:".$shop_map[$item['shop_id']],
                    'date' => $item['date'],
                    'quantity' => (int)$item['DisputeRate'] ?? 0,
                ];
                return $item_new;
            }, $list);
        } catch (\Exception $e) {
            $list_new = [];
        }
        return json(DefaultResponse(200, true, '获取成功', $list_new));
    }

    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function unmatcheds($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $tabstatus   = $params['tabstatus'] ?? 'All';
        $type   = $params['type'] ?? '';
        $date   = $params['date'] ?? [];
        $create_time   = $params['create_time'] ?? [];
        $createtime   = $params['createtime'] ?? [];
        $shop_id   = $params['shop_id'] ?? 0;
        $status   = $params['status'] ?? 0;
        $order_name   = $params['order_name'] ?? 0;
        $tracking_number   = $params['tracking_number'] ?? 0;
        $customDate = $params['customDate'] ?? 0;
        $where = [];
        $where[]  = ['disputetime', '=', 0];
        if(!empty($createtime)){
            $where[]  = ['createtime', '>=', strtotime($createtime[0])];
            $where[]  = ['createtime', '<=', strtotime($createtime[1]) + 3600*24-1];
        }
        if(!empty($shop_id)){
            $where[] = ['shop_id','=',$shop_id];
        }
        if(!empty($order_name)){
            $where[] = array('order_name', 'LIKE', '%' . trim($order_name) . '%');
        }
        if(!empty($tracking_number)){
            $where[] = array('tracking_number', 'LIKE', '%' . trim($tracking_number) . '%');
        }
        if(!empty($type)){
            if($type == 'MatchSuccessful'){
                $where[] = ['order_id','>',0];
            }
            if($type == 'WaitingForAMatch'){
                $where[] = ['order_id','<=',0];
            }
        }
        //日期
        $where = $this->ProcessingDate($date,$where,$customDate,$create_time);
        
        //统计
        $Statistics = $this->Statistics($where);
        
        $shops = Db::name('shops')->field('id,name')->select()->toarray();
        $shop_map = array_column($shops,'name','id');
        switch ($tabstatus) {
            case 'afterpay':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_afterpay')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                
                $totals = $list->total();
                break;
            case 'airwallex':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_airwallex')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'paypal':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_paypal')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'stripe':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_stripe')
                    ->where($where)
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'shopify':
                if(!empty($status)){
                    $status = $this->ChangeStatewhere($status,$tabstatus);
                    $where[] = ['status','=',$status];
                }
                $list = Db::name('order_dispute_api')
                    ->where($where)
                    ->group('dispute_id')
                    ->order("disputetime desc")
                    ->paginate($limit);
                $lists = $list->items();
                $totals = $list->total();
                break;
            case 'All':
                $tables = [
                    'order_dispute_afterpay',
                    'order_dispute_airwallex',
                    'order_dispute_paypal',
                    'order_dispute_stripe',
                    'order_dispute_api'
                ];
                
                $lists = [];
                $totals = 0;
                foreach ($tables as $table) {
                    // if(!empty($status)){
                    //     $status = $this->ChangeStatewhere($status,$tabstatus);
                    //     $where[] = ['status','=',$status];
                    // }
                    $list = Db::name($table)
                        ->where($where)
                        ->order("disputetime desc")
                        ->paginate($limit);
                    $total = $list->total();
                    $list = $list->items();
                    foreach ($list as &$v) {
                        switch ($table) {
                            case 'order_dispute_afterpay':
                                $v['tabstatus'] = 'afterpay';
                                break;
                            case 'order_dispute_airwallex':
                                $v['tabstatus'] = 'airwallex';
                                break;
                            case 'order_dispute_paypal':
                                $v['tabstatus'] = 'paypal';
                                break;
                            case 'order_dispute_stripe':
                                $v['tabstatus'] = 'stripe';
                                break;
                            case 'order_dispute_api':
                                $v['tabstatus'] = 'shopify';
                                break;
                            default:
                        }
                        
                    }
                    $totals += $total;
                    $lists = array_merge($lists, $list);
                }
                break;
            default:
        }
        foreach ($lists as &$v) {
            if($v['OrderDeliveryTime'] > 0){
                $v['OrderDeliveryTime'] = date('Y-m-d',strtotime($v['OrderDeliveryTime']));
            }else{
                $v['OrderDeliveryTime'] = "暂无";
            }
            if($v['createtime'] > 0){
                $v['createtime'] = date('Y-m-d',$v['createtime']);
            }else{
                $v['createtime'] = "暂无";
            }
            if($v['disputetime'] > 0){
                $v['time'] = date('Y-m-d',$v['disputetime']);
            }else{
                $v['time'] = "";
            }
            if($tabstatus !== "All"){
                $v['tabstatus'] = $tabstatus;
            }
            if($v['fulfillment_status'] == 'fulfilled'){
                $v['fulfillment_status'] = '已发货';
            }elseif($v['fulfillment_status'] == 'partial'){
                $v['fulfillment_status'] = '部分发货';
            }else{
                $v['fulfillment_status'] = '未发货';
            }
            $v['shop_id'] = $v['shop_id'] ?? 0;
            $v['shop_name'] = $shop_map[$v['shop_id']] ?? "";
            $v['status'] = $this->ChangeState($v['status'],$tabstatus);
        }
        $data = [
            'list' => $lists,
            'total' => $totals,
            'spends' => $Statistics['spends'],
            'spends_Total' => $Statistics['spends_Total'],
        ];

        return json(DefaultResponse(200, true, '获取成功', $data));
    }


}
